package cn.uniquetech.flex;

import java.util.List;

import cn.uniquetech.util.FileUtil;
import cn.uniquetech.vo.MySqlTableVO;

public class UQDPUtil {
	/**
	 * 包名
	 */
	private static final String packageName = "cn.uniquetech";
	/**
	 * 主键字段
	 */
	private static String key = "iid";
	/**
	 * 开头
	 */
	private static String headerStr = "\t";
	/**
	 * 结尾
	 */
	private static String tailStr = "\r\n";
	/**
	 * 生成实体中，要过滤的字段名称
	 */
	private static String filterFields = ",iid,cname,comment,adduid,adduname,adddate,edituid,edituname,editdate";

	/**
	 * SQL数据类型到Java数据类型的转换
	 * 
	 * @param fieldType
	 *            SQL数据类型
	 * @return Java数据类型
	 */
	public static String javaType(String fieldType) {
		String newType;
		if (fieldType.equalsIgnoreCase("varchar") || fieldType.equalsIgnoreCase("char"))
			newType = "String";
		else if (fieldType.equalsIgnoreCase("bigint"))
			newType = "Long";
		else if (fieldType.equalsIgnoreCase("int") || fieldType.equalsIgnoreCase("smallint"))
			newType = "int";
		else if (fieldType.equalsIgnoreCase("decimal"))
			newType = "double";
		else if (fieldType.equalsIgnoreCase("timestmp") || fieldType.equalsIgnoreCase("datetime") || fieldType.equalsIgnoreCase("date"))
			newType = "Date";
		else {
			newType = fieldType;
		}
		return newType;
	}

	// 生成java实体
	private static String scEntity(List<MySqlTableVO> list) {
		MySqlTableVO tableVO = list.get(0);
		String pk = packageName + ".entity";
		StringBuffer sb = new StringBuffer();
		sb.append("package " + pk + ";" + tailStr);
		sb.append("import cn.uniquetech.entity.base.BaseEntity;" + tailStr);
		sb.append("//" + tableVO.getTableComment() + tailStr);
		sb.append("@SuppressWarnings(\"serial\")" + tailStr);
		sb.append("public class " + tableVO.getVoName() + "Entity extends BaseEntity" + " {" + tailStr);
		scJavaAttr(sb, list);
		sb.append(tailStr);
		scGetSet(sb, list);
		sb.append("}" + tailStr);
		FileUtil.writeFile(pk, tableVO.getVoName() + "Entity.java", sb.toString());
		return sb.toString();
	}

	// 生成java属性
	private static void scJavaAttr(StringBuffer sb, List<MySqlTableVO> list) {
		for (MySqlTableVO tableVO : list) {
			String colName = tableVO.getColName();
			if (filterFields.indexOf("," + colName) != -1) {
				continue;
			}
			sb.append(headerStr + "//" + tableVO.getComment() + tailStr);
			sb.append(headerStr + "private " + javaType(tableVO.getDataType()) + " " + colName + ";" + tailStr);
		}
	}

	// 生成java get set
	private static void scGetSet(StringBuffer sb, List<MySqlTableVO> list) {
		for (MySqlTableVO tableVO : list) {
			String colName = tableVO.getColName();
			if (filterFields.indexOf("," + colName) != -1) {
				continue;
			}
			sb.append(genSetGet(javaType(tableVO.getDataType()), colName));
		}
	}

	// 生成set get
	private static String genSetGet(String colType, String colName) {
		String str = "";
		String capName = captureName(colName);
		str += headerStr + "public " + colType + " get" + capName + "(){" + tailStr + headerStr + headerStr + "return " + colName + ";" + tailStr + headerStr + "}" + tailStr + tailStr;
		str += headerStr + "public void set" + capName + "(" + colType + " " + colName + "){" + tailStr + headerStr + headerStr + "this." + colName + "=" + colName + ";" + tailStr + headerStr + "}" + tailStr + tailStr;
		return str;
	}

	// 首字母变大
	public static String captureName(String name) {
		char[] cs = name.toCharArray();
		cs[0] -= 32;
		return String.valueOf(cs);
	}

	// 生成flex vo
	private static String scFlexVO(List<MySqlTableVO> list) {
		MySqlTableVO tableVO = list.get(0);
		String pk = packageName + ".vo";
		StringBuffer sb = new StringBuffer();
		sb.append("package " + pk + tailStr + " {" + tailStr);
		sb.append(headerStr + "import cn.uniquetech.vo.base.BaseVO;" + tailStr);
		sb.append(headerStr + "//" + tableVO.getTableComment() + tailStr);
		sb.append(headerStr + "[Bindable]" + tailStr);
		sb.append(headerStr + "[RemoteClass(alias=\"cn.uniquetech.entity." + tableVO.getVoName() + "Entity\")] " + tailStr);
		sb.append(headerStr + "public class " + tableVO.getVoName() + "VO extends BaseVO" + tailStr + headerStr + " {" + tailStr);
		scFlexAttr(sb, list);
		sb.append(headerStr + "}" + tailStr);
		sb.append("}" + tailStr);
		FileUtil.writeFile(pk, tableVO.getVoName() + "VO.as", sb.toString());
		return sb.toString();
	}

	// 生成flex vo 属性
	private static void scFlexAttr(StringBuffer sb, List<MySqlTableVO> list) {
		for (MySqlTableVO tableVO : list) {
			String colName = tableVO.getColName();
			if (filterFields.indexOf("," + colName) != -1) {
				continue;
			}
			sb.append(headerStr + headerStr + "//" + tableVO.getComment() + tailStr);
			sb.append(headerStr + headerStr + "public var " + colName + ":" + javaType(tableVO.getDataType()) + ";" + tailStr);
		}
	}

	// 生成sqlxml
	private static String scSqlXml(List<MySqlTableVO> list) {
		MySqlTableVO tableVO = list.get(0);
		String tableName = tableVO.getTableName();
		String pk = packageName + ".entity.sqlmap";
		StringBuffer sb = new StringBuffer();
		String entityName = packageName + ".entity." + tableVO.getVoName() + "Entity";

		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + tailStr);
		sb.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">" + tailStr);
		sb.append("<mapper namespace=\"" + tableVO.getVoName() + "Mapper\">" + tailStr);

		sb.append(headerStr + "<!-- 插入实体 -->" + tailStr);
		sb.append(headerStr + "<insert id=\"addEntity\" parameterType=\"" + entityName + "\">" + tailStr);
		sb.append(headerStr + " " + scInsertSqlStr(list) + tailStr);
		sb.append(headerStr + "<selectKey keyProperty=\"iid\" resultType=\"int\" order=\"AFTER\">" + tailStr);
		sb.append(headerStr + "select LAST_INSERT_ID()" + tailStr);
		sb.append(headerStr + "</selectKey>" + tailStr);
		sb.append(headerStr + "</insert>" + tailStr);

		sb.append(headerStr + "<!-- 更新实体 -->" + tailStr);
		sb.append(headerStr + "<update id=\"updateEntity\" parameterType=\"" + entityName + "\">" + tailStr);
		sb.append(headerStr + " " + scUpdateSqlStr(list) + tailStr);
		sb.append(headerStr + "</update>" + tailStr);

		sb.append(headerStr + "<!-- 删除一个或多个实体-->" + tailStr);
		sb.append(headerStr + "<delete id=\"deleteEntity\" parameterType=\"string\">" + tailStr);
		sb.append(headerStr + " delete from " + tableName + " where " + key + " in (${_parameter})" + tailStr);
		sb.append(headerStr + "</delete>" + tailStr);

		sb.append(headerStr + "<!-- 获取单个实体 -->" + tailStr);
		sb.append(headerStr + "<select id=\"fecthOneEntity\" parameterType=\"int\" resultType=\"" + entityName + "\">" + tailStr);
		sb.append(headerStr + " select * from " + tableName + " where " + key + " = #{_parameter}" + tailStr);
		sb.append(headerStr + "</select>" + tailStr);

		sb.append(headerStr + "<!-- 查询实体集合 -->" + tailStr);
		sb.append(headerStr + "<select id=\"queryEntities\" parameterType=\"hashmap\" resultType=\"" + entityName + "\">" + tailStr);
		sb.append(headerStr + " select * from " + tableName + " order by " + key + " desc" + tailStr);
		sb.append(headerStr + "</select>" + tailStr);

		sb.append(headerStr + "<!-- 分页查询 -->" + tailStr);
		sb.append(headerStr + "<select id=\"queryDataGrid\" parameterType=\"hashmap\" resultType=\"" + entityName + "\">" + tailStr);
		sb.append(headerStr + " select * from " + tableName + " where 1=1  order by " + key + " desc limit  #{start},#{rows} " + tailStr);
		sb.append(headerStr + "</select>" + tailStr);

		sb.append(headerStr + "<select id=\"queryDataGrid_count\" parameterType=\"hashmap\" resultType=\"int\">" + tailStr);
		sb.append(headerStr + " select count(*) from " + tableName + " where 1=1 " + tailStr);
		sb.append(headerStr + "</select>" + tailStr);

		sb.append("</mapper>");
		FileUtil.writeFile(pk, tableVO.getVoName() + ".xml", sb.toString());
		return sb.toString();
	}

	// 生成insert
	private static String scInsertSqlStr(List<MySqlTableVO> list) {
		MySqlTableVO tableVO = list.get(0);
		String tableName = tableVO.getTableName();
		String sqlStr = "insert into " + tableName + " (";
		String fields = "";
		String values = "";

		for (MySqlTableVO vo : list) {
			String colName = vo.getColName();
			if (key.equals(colName)) {
				continue;
			}
			fields += colName + ",";
			values += "#{" + colName + "},";
		}

		fields = fields.substring(0, fields.length() - 1);
		values = values.substring(0, values.length() - 1);
		sqlStr += fields + ") " + tailStr;
		sqlStr += headerStr + " values " + tailStr;
		sqlStr += headerStr + "(" + values + ")";
		return sqlStr;
	}

	// 生成update语句
	private static String scUpdateSqlStr(List<MySqlTableVO> list) {
		MySqlTableVO tableVO = list.get(0);
		String tableName = tableVO.getTableName();
		String sqlStr = "update " + tableName + " set ";
		String fields = "";

		for (MySqlTableVO vo : list) {
			String colName = vo.getColName();
			if (key.equals(colName) || "adduid".equals(colName) || "adduname".equals(colName) || "adddate".equals(colName)) {
				continue;
			}
			fields += colName + "=#{" + colName + "},";
		}

		fields = fields.substring(0, fields.length() - 1);
		sqlStr += fields + "\r\n";
		sqlStr += headerStr + " where " + key + " =#{" + key + "}";
		return sqlStr;
	}

	// 生成service接口
	private static String scService(List<MySqlTableVO> list) {
		MySqlTableVO tableVO = list.get(0);
		String pk = packageName + ".service";
		StringBuffer sb = new StringBuffer();
		sb.append("package " + pk + ";" + tailStr);
		sb.append("import cn.uniquetech.service.base.IBaseService;" + tailStr);
		sb.append("//" + tableVO.getTableComment() + tailStr);
		sb.append("public interface I" + tableVO.getVoName() + "Service extends IBaseService" + "{" + tailStr);
		sb.append("}" + tailStr);
		FileUtil.writeFile(pk, "I" + tableVO.getVoName() + "Service.java", sb.toString());
		return sb.toString();
	}

	// service 生成实现类
	public static String scServiceClass(List<MySqlTableVO> list) {
		MySqlTableVO tableVO = list.get(0);
		String pk = packageName + ".service.impl";
		StringBuffer sb = new StringBuffer();
		sb.append("package " + pk + ";\r\n\r\n");
		String clazz = tableVO.getVoName();
		sb.append("import org.springframework.stereotype.Service;" + tailStr);
		sb.append("import cn.uniquetech.service.base.BaseServiceImpl;" + tailStr);
		sb.append("import cn.uniquetech.service.I" + clazz + "Service;");
		sb.append("\r\n\r\n");
		sb.append("//" + tableVO.getTableComment() + tailStr);
		sb.append("@Service");
		sb.append("\r\n");
		sb.append("public class " + clazz + "ServiceImpl extends BaseServiceImpl implements I" + clazz + "Service" + " {\r\n\r\n");
		sb.append("public " + clazz + "ServiceImpl() {\r\n");
		sb.append("\t\tsuper();\r\n");
		sb.append("\t\tthis.mapper = \"" + clazz + "Mapper\";\r\n");
		sb.append("\t}\r\n");
		sb.append("}\r\n");
		FileUtil.writeFile(pk, clazz + "ServiceImpl.java", sb.toString());
		return sb.toString();
	}

	// 生成controller
	private static String scController(List<MySqlTableVO> list) {
		MySqlTableVO tableVO = list.get(0);
		String pk = packageName + ".controller";
		String voName = tableVO.getVoName();
		StringBuffer sb = new StringBuffer();
		sb.append("package " + pk + ";" + tailStr + tailStr);
		sb.append("import org.springframework.beans.factory.annotation.Autowired;" + tailStr);
		sb.append("import org.springframework.flex.remoting.RemotingDestination;" + tailStr);
		sb.append("import org.springframework.web.bind.annotation.RestController;" + tailStr);
		sb.append("import cn.uniquetech.controller.base.BaseController;" + tailStr);
		sb.append("import cn.uniquetech.service.I" + voName + "Service;" + tailStr);
		sb.append("//" + tableVO.getTableComment() + tailStr);

		sb.append("@RestController" + tailStr);
		sb.append("@RemotingDestination(value = \"" + voName + "Dest\")" + tailStr);
		sb.append("public class " + voName + "Controller extends BaseController {" + tailStr);
		sb.append("public I" + voName + "Service " + voName.toLowerCase() + "Service;" + tailStr);

		sb.append("@Autowired" + tailStr);
		sb.append("public " + voName + "Controller(I" + voName + "Service " + voName.toLowerCase() + "Service) {" + tailStr);
		sb.append("this." + voName.toLowerCase() + "Service = " + voName.toLowerCase() + "Service;" + tailStr);
		sb.append("this.baseService = " + voName.toLowerCase() + "Service;" + tailStr);
		sb.append("}" + tailStr);
		sb.append("}" + tailStr);
		FileUtil.writeFile(pk, voName + "Controller.java", sb.toString());
		return sb.toString();
	}

	// 生成flex view
	private static String scFlexView(List<MySqlTableVO> list) {
		MySqlTableVO tableVO = list.get(0);
		String voName = tableVO.getVoName();
		String pk = packageName + ".view." + voName.toLowerCase();
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + tailStr);
		sb.append("<base:UQSysView xmlns:mx=\"http://www.adobe.com/2006/mxml\" xmlns:base=\"cn.uniquetech.base.*\" label=\""+tableVO.getTableComment()+"\" " + tailStr);
		sb.append("direction=\"vertical\" verticalGap=\"1\" width=\"100%\" height=\"100%\" xmlns:pager=\"cn.uniquetech.customer.pager.*\" xmlns:datagrid=\"cn.uniquetech.customer.datagrid.*\" xmlns:customer=\"cn.uniquetech.customer.*\" " + tailStr);
		sb.append("roDest=\"" + voName + "Dest\" window=\"{new " + voName + "Window}\" item=\"{new " + voName + "VO}\">" + tailStr);

		sb.append("<mx:Script>" + tailStr);
		sb.append("<![CDATA[" + tailStr);
		sb.append(headerStr + "import cn.uniquetech.vo." + voName + "VO;" + tailStr);
		sb.append("]]>" + tailStr);
		sb.append("</mx:Script>" + tailStr);

		sb.append("<mx:HBox width=\"100%\" height=\"30\" verticalAlign=\"middle\">" + tailStr);
		sb.append(headerStr + "<mx:FormItem label=\"query:\" labelWidth=\"40\">" + tailStr);
		sb.append(headerStr + headerStr + "<mx:TextInput id=\"query\" width=\"100\"/>" + tailStr);
		sb.append(headerStr + "</mx:FormItem>" + tailStr);
		sb.append(headerStr + "<mx:Button label=\"查询\" click=\"queryHandler()\"/>" + tailStr);
		sb.append(headerStr + "<mx:Button label=\"添加\" click=\"newHandler()\"/>" + tailStr);
		sb.append(headerStr + "<mx:Button label=\"修改\" click=\"editHandler()\"/>" + tailStr);
		sb.append(headerStr + "<mx:Button label=\"删除\" click=\"removeHandler()\"/>" + tailStr);
		sb.append("</mx:HBox>" + tailStr);

		sb.append("<mx:Canvas width=\"100%\" height=\"100%\">" + tailStr);
		sb.append(headerStr + "<datagrid:UQDataGrid id=\"dataGrid\" doubleClick=\"gridDoubleClickHandler(event)\" doubleClickEnabled=\"true\" width=\"100%\" height=\"100%\" textAlign=\"center\" dataProvider=\"{this.items}\">" + tailStr);
		sb.append(headerStr + headerStr + "<datagrid:columns>" + tailStr);

		sb.append(headerStr + headerStr + headerStr + "<mx:DataGridColumn labelFunction=\"xhlbfun\" headerText=\"序号\" width=\"60\"/>" + tailStr);

		for (MySqlTableVO mstvo : list) {
			sb.append(headerStr + headerStr + headerStr + "<mx:DataGridColumn dataField=\"" + mstvo.getColName() + "\" headerText=\"" + mstvo.getComment() + "\" width=\"80\"/>" + tailStr);
		}

		sb.append(headerStr + headerStr + "</datagrid:columns>" + tailStr);
		sb.append(headerStr + "</datagrid:UQDataGrid>" + tailStr);
		sb.append("</mx:Canvas>" + tailStr);
		sb.append("<pager:UQPagerView id=\"pagerView\" pageSize=\"35\"/>" + tailStr);
		sb.append("</base:UQSysView>");
		FileUtil.writeFile(pk, tableVO.getVoName() + "View.mxml", sb.toString());
		return sb.toString();
	}

	// 生成flex window
	private static String scFlexWindow(List<MySqlTableVO> list) {
		MySqlTableVO tableVO = list.get(0);
		String voName = tableVO.getVoName();
		String pk = packageName + ".view." + voName.toLowerCase();
		StringBuffer sb = new StringBuffer();

		sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + tailStr);
		sb.append("<base:UQSysWindow xmlns:mx=\"http://www.adobe.com/2006/mxml\" xmlns:base=\"cn.uniquetech.base.*\" " + tailStr);
		sb.append("layout=\"vertical\" width=\"700\" paddingLeft=\"5\" paddingRight=\"5\" paddingBottom=\"5\" paddingTop=\"5\" title=\""+tableVO.getTableComment()+"\">" + tailStr);

		int len = list.size();
		int xh = len / 3;
		System.out.println("-------len[" + len + "],xh[" + xh + "]");
		try {
			int curIndex = 0;
			for (int i = 0; i <= xh; i++) {
				System.out.println("----i[" + i + "]");
				sb.append(headerStr + "<mx:HBox width=\"100%\" verticalAlign=\"middle\" horizontalGap=\"1\" styleName=\"formItemHBox\">" + tailStr);
				for (int j = 0; j < 3; j++) {
					curIndex = i*3 + j;
					if (curIndex > len - 1) {
						break;
					}
					MySqlTableVO mstvo = list.get(curIndex);
					System.out.println("------index------[" + curIndex + "]");
					if (mstvo == null) {
						break;
					}

					sb.append(headerStr + headerStr + "<mx:FormItem label=\"" + mstvo.getComment() + ":\" labelWidth=\"80\" width=\"100%\" required=\"true\">" + tailStr);
					sb.append(headerStr + headerStr + headerStr + "<mx:TextInput id=\"" + mstvo.getColName() + "\" width=\"100%\" ");
					if(mstvo.getClen() != 0){
						sb.append("maxChars=\""+mstvo.getClen()+"\" toolTip=\""+mstvo.getTableComment()+mstvo.getComment()+",最长为"+mstvo.getClen()+"个字符"+"\" ");
					}else{
						sb.append("toolTip=\""+mstvo.getTableComment()+mstvo.getComment()+"\"");
					}
					sb.append(" tabIndex=\"" + curIndex + "\"/>" + tailStr);
					sb.append(headerStr + headerStr + "</mx:FormItem>" + tailStr);
				}
				sb.append(headerStr + "</mx:HBox>" + tailStr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		sb.append(headerStr + "<mx:ControlBar width=\"100%\" verticalAlign=\"middle\" horizontalAlign=\"center\">" + tailStr);
		sb.append(headerStr + headerStr + "<mx:Button id=\"btnHandler\" label=\"保存\" click=\"onSubmit()\"/>" + tailStr);
		sb.append(headerStr + headerStr + "<mx:Button id=\"btnClose\"   label=\"关闭\" click=\"onWindowClose()\"/>" + tailStr);
		sb.append(headerStr + "</mx:ControlBar>" + tailStr);
		sb.append("</base:UQSysWindow>");

		FileUtil.writeFile(pk, tableVO.getVoName() + "Window.mxml", sb.toString());
		return sb.toString();
	}

	public static void sc(List<MySqlTableVO> list) {
		String str = "";
		str = scEntity(list);
		str += scFlexVO(list);
		str += scSqlXml(list);
		str += scService(list);
		str += scServiceClass(list);
		str += scController(list);
		str += scFlexView(list);
		str += scFlexWindow(list);
		System.out.println(str);
	}

}
